<!--
 * @Description:树的弹窗组件
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-12-07 15:54:35
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-01-25 14:50:32
-->
<template>
  <div class="treeDialog z-w-100">
    <el-button
      type="primary"
      icon="el-icon-suitcase"
      size="small"
      @click="btnClick"
    >
      选择菜单
    </el-button>
    <baseDialog
      ref="baseDialog"
      title="选择菜单"
      @comfire="comfireFun"
    >
      <template slot="content">
        <baseTree
          ref="baseTree"
          :value="treeValue"
          :data="data"
          :props="treeProps"
          show-checkbox
        />
      </template>
    </baseDialog>
  </div>
</template>

<script>
import baseDialog from '@/components/baseDialog/index.vue'
import baseTree from '@/components/baseTree/index.vue'
import { getAllMenu } from '@/api/menu'
import { listToTree } from '@/store/rouerConfig.js'
export default {
  name: 'TreeDialog',
  components: {
    baseDialog,
    baseTree
  },
  props: {
    value: {
      type: [String, Array],
      default: ''
    },
    params: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      data: [],
      treeProps: {
        children: 'children',
        label: 'mName'
      },
      treeValue: []
    }
  },
  created () {
    this.getAllMenu()
  },
  methods: {
    // 弹窗确定按钮
    comfireFun () {
      const targetData = this.$refs.baseTree.getCheckedNodes()
      this.treeValue = targetData
      console.log(this.treeValue, 's')
      this.$emit('input', this.treeValue)
    },

    async getAllMenu () {
      const res = await getAllMenu()
      if (res.code === '0') {
        this.data = listToTree(res.data, { pId: 'parentId' })
      }
      this.setDefaultValue()
    },
    setDefaultValue () {
      console.log(this.value, 'this.valuethis.value')
      if (this.value && this.value.length > 0) {
        const selectTreeData = listToTree(this.value, { pId: 'parentId' })
        this.treeValue = this.getNodeData(selectTreeData)
      } else {
        this.treeValue = []
      }
    },
    getNodeData (treeData, result = []) {
      if (!treeData || treeData.length === 0) {
        return result
      }
      for (let i = 0; i < treeData.length; i++) {
        const target = treeData[i]
        if (!target.children || target.children.length === 0) {
          result.push(target)
        }
        if (target.children && target.children.length > 0) {
          this.getNodeData(target.children, result)
        }
      }
      return result
    },
    btnClick () {
      this.$refs.baseDialog.dialogVisible = true
    }
  }
}
</script>

<style>

</style>
